package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.minio.service.FileOpsService;
import com.atguigu.tingshu.common.minio.service.impl.FileOpsServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Author:huzhongkui
 * Date: 2025-01-14 星期二 15:13:38
 * Description:  minio的自动配置类
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio",havingValue = "true",value = "enable")
public class MinioAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class);

    /**
     * 定义一个MinIOClient的Bean对象
     */
    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {


        // 1.创建minio客户端用于和minio进行通信
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(minioProperties.getEndpointUrl())  // minio服务器的地址在哪里
                        .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                        .build();

        boolean found = false;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println(minioProperties.getBucketName() + "already exists.");
            }
            return minioClient;
        } catch (Exception e) {
            logger.error("minio对象初始化失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }


    @Bean
    public FileOpsService fileOpsService() {
        return new FileOpsServiceImpl();
    }


}
